import Vue from "vue";
import Router from "vue-router";
import Home from "views/Home.vue";
import store from "@/store";

let routes = [
  {
    path: "/",
    name: "home",
    component: Home,
    meta: {
      title: "工程项目管理模块"
    }
  },
  {
    path: "/cusAddDocsList",
    name: "cusAddDocsList",
    component: r =>
      require.ensure(
        [],
        () => r(require("views/CusAddDocs/CusAddDocsList.vue")),
        "cusAddDocsList"
      ),
    meta: {
      title: "客户建档查询"
    }
  },
  {
    path: "/cusAddDocsDetail",
    name: "cusAddDocsDetail",
    component: r =>
      require.ensure(
        [],
        () => r(require("views/CusAddDocs/CusAddDocsDetail.vue")),
        "cusAddDocsDetail"
      ),
    meta: {
      title: "客户档案详情"
    }
  },
  {
    path: "/projectPurchaseList",
    name: "projectPurchaseList",
    component: r =>
      require.ensure(
        [],
        () => r(require("views/ProjectPurchase/ProjectPurchaseList.vue")),
        "projectPurchaseList"
      ),
    meta: {
      title: "集采项目报备查询"
    }
  },
  {
    path: "/projectPurchaseDetail",
    name: "projectPurchaseDetail",
    component: r =>
      require.ensure(
        [],
        () => r(require("views/ProjectPurchase/ProjectPurchaseContainer.vue")),
        "projectPurchaseDetail"
      ),
    meta: {
      title: "集采项目报备详情"
    }
  },
  {
    path: "/projectReportList",
    name: "projectReportList",
    component: r =>
      require.ensure(
        [],
        () => r(require("views/ProjectReport/ProjectReportList.vue")),
        "projectReportList"
      ),
    meta: {
      title: "项目报备查询"
    }
  },
  {
    path: "/projectReportDetail",
    name: "projectReportDetail",
    component: r =>
      require.ensure(
        [],
        () => r(require("views/ProjectReport/ProjectReportDetailCon.vue")),
        "projectReportDetail"
      ),
    meta: {
      title: "项目报备详情"
    }
  },
  {
    path: "/bidManagement",
    name: "bidManagement",
    component: r =>
      require.ensure(
        [],
        () => r(require("views/BidManagement/BidList.vue")),
        "bidManagementList"
      ),
    meta: {
      title: "投标管理"
    }
  },
  {
    path: "/bidDetail",
    name: "bidDetail",
    component: r =>
      require.ensure(
        [],
        () => r(require("views/BidManagement/BidDetail.vue")),
        "bidDetail"
      ),
    meta: {
      title: "投标管理"
    }
  },
  {
    path: "/contractList",
    name: "contractList",
    component: r =>
      require.ensure(
        [],
        () => r(require("views/ContractManagement/ContractList.vue")),
        "contractList"
      ),
    meta: {
      title: "合同管理"
    }
  },
  {
    path: "/contractDetail",
    name: "contractDetail",
    component: r =>
      require.ensure(
        [],
        () =>
          r(require("views/ContractManagement/ContractDetailContainer.vue")),
        "contractDetailContainer"
      ),
    meta: {
      title: "合同管理"
    }
  },
  {
    path: "/404",
    name: "404",
    component: r =>
      require.ensure([], () => r(require("views/404.vue")), "404"),
    meta: {
      title: "404",
      keepAlive: true
    }
  }
];

// const routerContext = require.context('./', true, /\.js$/)
// routerContext.keys().forEach(route => {
//   // 如果是根目录的 index.js 、不处理
//   if (route.startsWith('./index')) {
//     return
//   }
//   const routerModule = routerContext(route)
//   /**
//    * 兼容 import export 和 require module.export 两种规范
//    */
//   routes = routes.concat(routerModule.default || routerModule)
// })

routes = routes.concat({
  path: "*",
  redirect: "/404"
});

const createRouter = () =>
  new Router({
    // mode: 'history', // require service support
    base: process.env.BASE_URL,
    scrollBehavior: () => ({ y: 0 }),
    routes
  });

const myRouter = createRouter();

// const myRouter = new Router({
//   mode: 'history',
//   base: process.env.BASE_URL,
//   routes
// })

const history = window.sessionStorage;
// history.clear()
let historyCount = history.getItem("count") * 1 || 0;
history.setItem("/", 0);

myRouter.beforeEach((to, from, next) => {
  console.log(to, from);
  if (to.params.direction) {
    store.commit("updateDirection", to.params.direction);
  } else {
    const toIndex = history.getItem(to.path);
    const fromIndex = history.getItem(from.path);
    // 判断并记录跳转页面是否访问过，以此判断跳转过渡方式
    if (toIndex) {
      if (
        !fromIndex ||
        parseInt(toIndex, 10) > parseInt(fromIndex, 10) ||
        (toIndex === "0" && fromIndex === "0")
      ) {
        store.commit("updateDirection", "forward");
      } else {
        store.commit("updateDirection", "back");
      }
    } else {
      ++historyCount;
      history.setItem("count", historyCount);
      to.path !== "/" && history.setItem(to.path, historyCount);
      store.commit("updateDirection", "forward");
    }
  }
  next();
});

/* 路由异常错误处理，尝试解析一个异步组件时发生错误，重新渲染目标页面 */
myRouter.onError(error => {
  console.log("routerError:", error);
  const pattern = /Loading chunk (.*)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  const targetPath = myRouter.history.pending.fullPath;
  if (isChunkLoadFailed) {
    console.log(location);
    // myRouter.replace(targetPath);
    location.replace(location.href);
    // window.location.reload();
  }
});

Vue.use(Router);

export function resetRouter() {
  myRouter.replace("/login");
}

export default myRouter;
